package com.hello.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.hello.common.Constant;
import com.hello.modes.LoginForm;

@Controller
public class IndexController {
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index() {
		return "home";
	}

	@RequestMapping(value = "/login")
	public String login(@ModelAttribute("loginForm") LoginForm loginForm,
			Model model) {
		return "login";
	}

	@RequestMapping(value = "/checklogin")
	public String checklogin(@ModelAttribute("loginForm") LoginForm loginForm,
			Model model, HttpServletResponse response) {
		String username = loginForm.getUsername();
		String password = loginForm.getPassword();
		boolean isRemember = loginForm.isRemember();

		if ((username.equals(Constant.USER_ADMIN))
				&& (password.equals(Constant.PASSWORD))) {
			if (isRemember == Boolean.TRUE) {
				Cookie user = new Cookie("user", username);
				user.setMaxAge(60 * 60 * 60 * 24);

				Cookie pass = new Cookie("password", password);
				pass.setMaxAge(60 * 60 * 60 * 24);

				response.addCookie(user);
				response.addCookie(pass);
			}
			return "loginSuccess";
		} else {
			return "login";
		}
	}
}
